package testpluginfile.popup.utils;

import java.io.File;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

public class EclipseUtils {

	public static IFile getFileSelected() {
	IFile ifileSrc = null ;
	IWorkbench wb = PlatformUI.getWorkbench();
	IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
	ISelection  selection  = window.getSelectionService().getSelection() ;		
	if (selection instanceof IStructuredSelection) {
        IStructuredSelection ssel = (IStructuredSelection) selection;
        Object obj = ssel.getFirstElement();
        ifileSrc = (IFile) Platform.getAdapterManager().getAdapter(obj, IFile.class);
        if (ifileSrc == null) {
            if (obj instanceof IAdaptable) {
                ifileSrc = (IFile) ((IAdaptable) obj).getAdapter(IFile.class);
            }
        }
	}
	return ifileSrc ;
	}
	
	
	public static void refreshFile(File outputFile, IContainer parent,IProject project) {
		//IProject project2 = parent.getProject();
		IPath location= Path.fromOSString(outputFile.getAbsolutePath());
		IFile ifileConverti = project.getWorkspace().getRoot().getFileForLocation(location);						
		if (ifileConverti.exists()) {
			System.out.println(ifileConverti.getFullPath() + " ifile existe");
			try {
				ifileConverti.refreshLocal(IResource.DEPTH_ZERO, null);
				System.out.println(ifileConverti.getFullPath() + " rafraichit");
			} catch (CoreException e) {
				e.printStackTrace();
			}							
		}
		else {
			System.out.println(ifileConverti.getFullPath() + " ifile existe pas on va rafraichir le repertoire");
			IFolder folderFileToconvert = null ;
			if (parent instanceof IFolder ) {
				folderFileToconvert = (IFolder) parent;
				try {
					folderFileToconvert.refreshLocal(IResource.DEPTH_ONE, null);
					System.out.println(folderFileToconvert.getName() +  "rafraichit ");									
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}
			else if (parent instanceof IProject ) {
				System.out.println("parent = projet on va le refraichir " );
				try {					
					project.refreshLocal(IResource.DEPTH_ONE, null);
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}							
		}						
	}	
	
	
}
